package com.yinsin.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import com.yinsin.utils.ByteUtils;
import com.yinsin.utils.StreamUtils;

public class RSA2048 {

	static final String KEY_ALGORITHM = "RSA";
	/** 貌似默认是RSA/NONE/PKCS1Padding，未验证 */
	static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
	static final String PUBLIC_KEY = "publicKey";
	static final String PRIVATE_KEY = "privateKey";

	/** RSA密钥长度必须是64的倍数，在512~65536之间。默认是1024 */
	static final int KEY_SIZE = 2048;
	static final int PLAIN_LEN_2048 = 245; // 随着KEY_SIZE变化而变化，2048 = 245，1024 =
											// 117
	static final int CIPHER_LEN_2048 = 256; // 随着KEY_SIZE变化而变化，2048 = 256，1024 =
											// 128

	/**
	 * 公钥加密
	 * 
	 * @param publicKey 公钥
	 * @param plainText 明文
	 * @return byte[]
	 * @throws Exception 异常
	 */
	public static byte[] RSAEncode(String publicKey, byte[] plainText) throws Exception {
		try {
			PublicKey key = getPublicKeyFromX509(new ByteArrayInputStream(publicKey.getBytes()));
			return RSAEncode(key, plainText);
		} catch (Exception e) {
			throw new Exception("RSA加密异常：" + e.getMessage(), e);
		}
	}

	/**
	 * 公钥加密
	 * 
	 * @param publicKey 公钥
	 * @param plainText 明文
	 * @return byte[]
	 * @throws Exception 异常
	 */
	public static byte[] RSAEncode(PublicKey publicKey, byte[] plainText) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			int inputLen = plainText.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			for (int i = 0; inputLen - offSet > 0; offSet = i * PLAIN_LEN_2048) {
				if (inputLen - offSet > PLAIN_LEN_2048) {
					cache = cipher.doFinal(plainText, offSet, PLAIN_LEN_2048);
				} else {
					cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
				}

				out.write(cache, 0, cache.length);
				++i;
			}
			return out.toByteArray();
		} catch (Exception e) {
			throw new Exception("RSA加密异常：" + e.getMessage(), e);
		}
	}

	/**
	 * 私钥解密
	 * 
	 * @param privateKey 私钥
	 * @param encodedText 密文
	 * @return String
	 * @throws Exception 异常
	 */
	public static String RSADecode(String privateKey, byte[] encodedText) throws Exception {
		try {
			PrivateKey key = getPrivateKeyFromPKCS8(new ByteArrayInputStream(privateKey.getBytes()));
			return RSADecode(key, encodedText);
		} catch (Exception e) {
			throw new Exception("RSA解密异常：" + e.getMessage(), e);
		}
	}

	/**
	 * 私钥解密
	 * 
	 * @param privateKey 私钥
	 * @param encodedText 加密字符
	 * @return String
	 * @throws Exception 异常
	 */
	public static String RSADecode(PrivateKey privateKey, byte[] encodedText) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			int inputLen = encodedText.length;
			int offSet = 0;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] cache;
			for (int i = 0; inputLen - offSet > 0; offSet = i * CIPHER_LEN_2048) {
				if (inputLen - offSet > CIPHER_LEN_2048) {
					cache = cipher.doFinal(encodedText, offSet, CIPHER_LEN_2048);
				} else {
					cache = cipher.doFinal(encodedText, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				++i;
			}
			byte[] result = out.toByteArray();
			return new String(result);
		} catch (Exception e) {
			throw new Exception("RSA解密异常：" + e.getMessage(), e);
		}
	}

	/**
	 * 还原公钥，X509EncodedKeySpec 用于构建公钥的规范
	 * 
	 * @param keyBytes
	 * @return
	 * @throws Exception
	 */
	public static PublicKey restorePublicKey(byte[] keyBytes) throws Exception {

		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
		try {
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
			return publicKey;
		} catch (Exception e) {
			throw new Exception("公钥数据异常：" + e.getMessage(), e);
		}
	}

	/**
	 * 还原私钥，X509EncodedKeySpec 用于构建私钥的规范
	 * 
	 * @param keyBytes
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey restorePrivateKey(byte[] keyBytes) throws Exception {
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
		try {
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
			return privateKey;
		} catch (Exception e) {
			throw new Exception("私钥数据异常：" + e.getMessage());
		}

	}

	/**
	 * 私钥加密。
	 * 
	 * @param key
	 * @param plainText
	 * @return
	 * @throws Exception
	 */
	public static byte[] RSAEncode(PrivateKey key, byte[] plainText) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] byts = null, result = new byte[0];
			int size = plainText.length, len = PLAIN_LEN_2048;
			for (int i = 0; i < size; i += PLAIN_LEN_2048) {
				if (i + PLAIN_LEN_2048 > size) {
					len = size - i;
				}
				byts = ByteUtils.getByte(plainText, i, len);
				byts = cipher.doFinal(byts);
				result = ByteUtils.joinByteArray(result, byts);
			}
			return result;
		} catch (Exception e) {
			throw new Exception("RSA加密异常：" + e.getMessage());
		}
	}

	/**
	 * 公钥解密。
	 * 
	 * @param key
	 * @param encodedText
	 * @return
	 * @throws Exception
	 */
	public static String RSADecode(PublicKey key, byte[] encodedText) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, key);
			int size = encodedText.length;
			byte[] byts = null, result = new byte[0];
			;
			for (int i = 0; i < size; i += CIPHER_LEN_2048) {
				byts = ByteUtils.getByte(encodedText, i, CIPHER_LEN_2048);
				byts = cipher.doFinal(byts);
				result = ByteUtils.joinByteArray(result, byts);
			}
			return new String(result);
		} catch (Exception e) {
			throw new Exception("RSA解密异常：" + e.getMessage());
		}
	}

	/**
	 * 从PKCS8文件中获取私钥对象
	 * 
	 * @param ins
	 *            输入流
	 * @return PrivateKey 私钥
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKeyFromPKCS8(InputStream ins) throws Exception {
		if (ins == null) {
			return null;
		}
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] encodedKey = StreamUtils.readText(ins).getBytes();
		encodedKey = Base64.getDecoder().decode(encodedKey);
		return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
	}

	/**
	 * 从X509证书中获取公钥
	 * 
	 * @param ins
	 *            输入流
	 * @return PublicKey 公钥
	 * @throws Exception
	 */
	public static PublicKey getPublicKeyFromX509(InputStream ins) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		StringWriter writer = new StringWriter();
		StreamUtils.io(new InputStreamReader(ins), writer);
		byte[] encodedKey = writer.toString().getBytes();
		encodedKey = Base64.getDecoder().decode(encodedKey);
		return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
	}
	
	/**
	 * 从公钥字节串中获取公钥
	 * 
	 * @param pubKeyBytes
	 *            公钥字节串
	 * @return PublicKey 公钥
	 * @throws Exception
	 */
	public static PublicKey getPublicKeyFromX509(byte[] pubKeyBytes) throws Exception {
		if (pubKeyBytes != null && pubKeyBytes.length > 0) {
			PublicKey pubkey = getPublicKeyFromX509(new ByteArrayInputStream(pubKeyBytes));
			return pubkey;
		}
		return null;
	}

}
